<template>
  <el-drawer v-model="visible" :title="isEdit ? '编辑管理员' : '添加管理员'" direction="rtl" size="500px"
    :before-close="handleClose">
    <div class="drawer-content">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="top">
        <!-- 头像上传 -->
        <el-form-item label="头像">
          <div class="avatar-upload">
            <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false"
              :on-change="handleAvatarChange" accept="image/*">
              <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <div class="avatar-tips">
              <p>点击上传头像</p>
              <p>支持jpg、png格式，大小不超过2MB</p>
            </div>
          </div>
        </el-form-item>

        <!-- 基本信息 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入管理员姓名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
        </el-form-item>

        <!-- <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" placeholder="请选择角色" multiple style="width: 100%">
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.name" :value="role.id"
              :disabled="role.disabled" />
          </el-select>
          <div class="form-tip">可以为管理员分配多个角色</div>
        </el-form-item> -->

        <el-form-item label="部门" prop="department">
          <el-select v-model="formData.department" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="dept in departmentOptions" :key="dept.value" :label="dept.label" :value="dept.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="工号" prop="employeeId">
          <el-input v-model="formData.employeeId" placeholder="请输入工号" />
        </el-form-item>

        <!-- 密码设置（仅新增时显示） -->
        <el-form-item v-if="!isEdit" label="登录密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" show-password />
        </el-form-item>

        <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
        </el-form-item>

        <!-- 状态设置 -->
        <el-form-item label="账户状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="正常">正常</el-radio>
            <el-radio value="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  adminData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const defaultFormData = {
  id: null,
  name: '',
  email: '',
  // roleIds: [],
  department: '',
  phone: '',
  employeeId: '',
  password: '',
  confirmPassword: '',
  status: '正常',
  avatar: '',
  remark: ''
}

const formData = reactive({ ...defaultFormData })

// 角色选项（从接口获取）
// const roleOptions = ref([
//   { id: 1, name: '超级管理员', disabled: true },
//   { id: 2, name: '系统管理员', disabled: false },
//   { id: 3, name: '内容管理员', disabled: false },
//   { id: 4, name: '审核员', disabled: false }
// ])

// 部门选项
const departmentOptions = [
  { label: '技术部', value: '技术部' },
  { label: '运营部', value: '运营部' },
  { label: '教务部', value: '教务部' },
  { label: '市场部', value: '市场部' },
  { label: '人事部', value: '人事部' }
]

// 表单验证规则
const formRules = computed(() => {
  const rules = {
    name: [
      { required: true, message: '请输入管理员姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    // roleIds: [
    //   { required: true, message: '请选择角色', trigger: 'change' }
    // ],
    department: [
      { required: true, message: '请选择部门', trigger: 'change' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    employeeId: [
      { required: true, message: '请输入工号', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择账户状态', trigger: 'change' }
    ]
  }

  // 新增时添加密码验证
  if (!props.isEdit) {
    rules.password = [
      { required: true, message: '请输入登录密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
    rules.confirmPassword = [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== formData.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  return rules
})

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (props.isEdit && props.adminData) {
      // 编辑模式，填充数据
      Object.assign(formData, {
        ...defaultFormData,
        ...props.adminData,
        confirmPassword: '' // 编辑时不需要确认密码
      })
    } else {
      // 新增模式，重置表单
      Object.assign(formData, defaultFormData)
    }

    // 重置表单验证
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
})

// 方法
const handleAvatarChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }

  // 这里应该上传到服务器，现在用本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.avatar = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    submitting.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 提交数据
    const submitData = { ...formData }
    delete submitData.confirmPassword // 不提交确认密码字段

    emit('submit', submitData)

    ElMessage.success(props.isEdit ? '更新成功' : '添加成功')
    handleClose()

  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped lang="scss">
.drawer-content {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.avatar-upload {
  display: flex;
  align-items: flex-start;
  gap: 16px;

  .avatar-uploader {
    .avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      object-fit: cover;
      border: 2px solid #dcdfe6;
    }

    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409EFF;
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
    }
  }

  .avatar-tips {
    flex: 1;
    font-size: 12px;
    color: #666;
    line-height: 1.4;

    p {
      margin: 0 0 4px 0;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px 20px 16px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-drawer__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-radio-group) {
  .el-radio {
    margin-right: 24px;
  }
}

:deep(.el-select__tags) {
  max-width: 100%;
}
</style>
